//
//  MyVedioPlayer.m
//  封装播放器
//
//  Created by dllo on 16/3/21.
//  Copyright © 2016年 厉程. All rights reserved.
//

#import "MyVedioPlayer.h"


@interface MyVedioPlayer ()




@property (retain, nonatomic)  UIButton *playButton;

@property (retain, nonatomic)  UISlider *progressSlider;

@property (retain, nonatomic)  UILabel *timeRightLabel;

@property (retain, nonatomic)  UILabel *timeLeftLabel;

@property (nonatomic, assign) CGFloat totalDuration;


@property (nonatomic, assign) BOOL p;
@property (nonatomic, assign) BOOL fullS;

@end


@implementation MyVedioPlayer

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}



+ (MyVedioPlayer *)shareVedioPlayer{
    
    static MyVedioPlayer *myVedioPlayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        myVedioPlayer = [[MyVedioPlayer alloc]init];
   
        
    });
    
    return myVedioPlayer;
}




- (void)setPlayViewWithframe:(CGRect )layerRect string:(NSString *)str{
    
    NSString *string = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:string];
    

    //创建播放项目对象
    self.playerItem = [[AVPlayerItem alloc]initWithURL:url];

        self.player = [[AVPlayer alloc]initWithPlayerItem:_playerItem];

    
    
    
    //   创建播放器对象
//    self.player = [[AVPlayer alloc]initWithPlayerItem:_playerItem];
//    [_player replaceCurrentItemWithPlayerItem:_playerItem];
    
    //    创建承载播放器的layer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    self.playerLayer.frame = CGRectMake(0, 0, layerRect.size.width, layerRect.size.height);

    
    
    //    设置视频填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;  //需要一个字符串
    
    self.playView = [[UIView alloc]initWithFrame:layerRect];
        _playView.backgroundColor = [UIColor blackColor];
    
    //    将播放器放到playView上
    [self.playView.layer insertSublayer:self.playerLayer atIndex:0];

    
    UITapGestureRecognizer *tapPlayView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapPlayViewAction)];
    
    [_playView addGestureRecognizer:tapPlayView];
    
    
    [self setControlsFrame];
    
    [self.player play];
    
    
 }




- (void)setControlsFrame{
    
    //    初始化控件
    
    self.p = 1;
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _playView.bounds.size.height - 35, _playView.bounds.size.width, 35)];
    
    _bottomView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [_playView addSubview:_bottomView];
    _bottomView.hidden = YES;
    
    
//    播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake((_playView.bounds.size.width - 50)/2, (_playView.bounds.size.height - 50)/2, 50, 50);

    
    _playButton.layer.cornerRadius = 25;
    
    _playButton.layer.borderColor = [UIColor whiteColor].CGColor;
    _playButton.layer.borderWidth = 0.5;
    [_playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _playButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
//    [_playButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang-2.png"] forState:UIControlStateNormal ];
            [_playButton setImage:[UIImage imageNamed:@"iconfont-pause.png"] forState:UIControlStateNormal];
    
    [self.playView addSubview:_playButton];
    _playButton.hidden = YES;
    
    
    
    
    self.playTimesLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, _bottomView.frame.size.width * 0.6, 25)];
    
    _playTimesLabel.textColor = [UIColor whiteColor];
    _playTimesLabel.font = [UIFont systemFontOfSize:13];
//    [_bottomView addSubview:_playTimesLabel];
    
    
    self.buttonFullScreen = [UIButton buttonWithType:UIButtonTypeCustom];
    _buttonFullScreen.frame = CGRectMake(_bottomView.frame.size.width - 35, 0, 35, 35);
    [_buttonFullScreen setImage:[UIImage imageNamed:@"iconfont-quanping.png"] forState:UIControlStateNormal];
    
    [_buttonFullScreen addTarget:self action:@selector(buttonFullScreenAction:) forControlEvents:UIControlEventTouchUpInside];
//    [_bottomView addSubview:_buttonFullScreen];
    
    
    self.timeLeftLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 50, 25)];
    _timeLeftLabel.text = @"00:00";
    _timeLeftLabel.textAlignment = NSTextAlignmentCenter;
    _timeLeftLabel.textColor = [UIColor whiteColor];
    [_bottomView addSubview:_timeLeftLabel];
//    _timeLeftLabel.hidden = YES;
    
    
    self.timeRightLabel = [[UILabel alloc]initWithFrame:CGRectMake( _buttonFullScreen.frame.origin.x - 60, 5, 50, 25)];
    
//    _timeRightLabel.text = @"--:--";
    _timeRightLabel.textAlignment = NSTextAlignmentCenter;
    _timeRightLabel.textColor = [UIColor whiteColor];
    [_bottomView addSubview:_timeRightLabel];
    
//    
//        CGFloat duration = CMTimeGetSeconds(_playerItem.duration);
//    _timeRightLabel.text = [NSString stringWithFormat:@"%02d:%02d", (int)duration/60, (int)duration%60];

    

    self.progressSlider = [[UISlider alloc]initWithFrame:CGRectMake(_timeLeftLabel.frame.origin.x + _timeLeftLabel.frame.size.width + 10, 5, _timeRightLabel.frame.origin.x - 20 - (_timeLeftLabel.frame.origin.x + _timeLeftLabel.frame.size.width) , 25)];
    
    
    [_progressSlider setThumbImage:[UIImage imageNamed:@"ball.png"] forState:UIControlStateNormal];
    _progressSlider.minimumValue = 0;
    _progressSlider.maximumValue = 1;
    _progressSlider.value = 0;
    [_bottomView addSubview:_progressSlider];
    [_progressSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
//    _progressSlider.hidden = YES;
    
    
    
    //    添加进度监听
    [self addProgressObserver];
    
}



//slider滑动方法
- (void)sliderAction:(UISlider *)slider{
    
    //    获取到当前进度时间
    CGFloat currentTime = self.totalDuration *slider.value;
    
    //    转化为CMTime
    CMTime dragTime = CMTimeMake(currentTime, 1);
    
    [self.player seekToTime:dragTime completionHandler:^(BOOL finished) {
        //        到了时间之后， 开始播放
        [self.player play];
    }];
    
    
}





//进度监听方法
- (void)addProgressObserver{
    
    __strong typeof(self) weakSelf = self;
    
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
    CGFloat duration = CMTimeGetSeconds(weakSelf.playerItem.duration);
                weakSelf.totalDuration = duration;
        
        
        CGFloat current = CMTimeGetSeconds(weakSelf.playerItem.currentTime);

    
   weakSelf.timeLeftLabel.text = [NSString stringWithFormat:@"%02d:%02d", (int)current/60, (int)current%60];
 
   weakSelf.timeRightLabel.text = [NSString stringWithFormat:@"%02d:%02d", (int)duration/60, (int)duration%60];

        weakSelf.progressSlider.value = current /duration;

        
    }];
}



//全屏按钮的点击方法
- (void)buttonFullScreenAction:(UIButton *)button{
    
//    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
//        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
//        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
//        //        _bottom.hidden = NO;
//        //        _seg.hidden = NO;
//        //        _myVedioPlayer.playerLayer.frame = CGRectMake(0, 0, SCREENW, SCREENH / 2 - 70 * ht);
//        //        _myVedioPlayer.playView.frame = CGRectMake(0, 64, SCREENW, SCREENH / 2 - 70 * ht);
//        
//        _bottomView.hidden = YES;
//        
//        CGRect rect = CGRectMake(0, 64, SCREENW, SCREENH - 64);
//        
////        [self setPlayViewWithframe:rect string:_model.origin_video[@"url_list"][0][@"url"]];
//        //        [self addSubview:_myVedioPlayer.playView];
//        _playerLayer.frame = CGRectMake(0, 0, SCREENW, SCREENH - 64);
//        _playView.frame = CGRectMake(0, 64, SCREENW, SCREENH - 64);
//        
//        [self.playView.layer insertSublayer:self.playerLayer atIndex:0];
//
//        
////        for (UIView* next = [self superview]; next; next = next.superview) {
//            UIResponder* nextResponder = [next nextResponder];
//            if ([nextResponder isKindOfClass:[UIViewController class]]) {
//                UIViewController *vv = (UIViewController*)nextResponder;
//                [vv.view addSubview:_myVedioPlayer.playView];
//            }
//        }
    
        
        
        //        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 2 - 105 * ht, WIDTH, 35 * ht);
        //        UIImageView *imageView = [_tableView viewWithTag:1000];
        //        imageView.frame = CGRectMake(10 * wt, 5 * ht, 50 * wt, 50 * ht);
        //        imageView.backgroundColor = [UIColor clearColor];
        //        imageView.layer.cornerRadius = 25;
        //        UILabel *name = [_tableView viewWithTag:2000];
        //        name.frame = CGRectMake(65 * wt, 20 * ht, SCREEN_WIDTH / 2, 20 * ht);
        //        UILabel *total = [_tableView viewWithTag:3000];
        //        total.frame = CGRectMake(10 * wt, 60 * ht, SCREEN_WIDTH, 20 * ht);
        //        UILabel *regData = [_tableView viewWithTag:4000];
        //        regData.frame = CGRectMake(10 * wt, 85 * ht, SCREEN_WIDTH, 20 * ht);
        //        self.playerLayer.frame =  CGRectMake(5, 5,[UIScreen mainScreen].bounds.size.width - 10,self.playView.frame.size.height -10);
        //
        //        _play.frame = CGRectMake(20 * wt, 0, 30 * wt, 30 * ht);
        //
        //        self.progressSlider.frame = CGRectMake(50 * wt, 0, WIDTH - 130 * wt, 30 * ht);
        //
        //        self.timeLable.frame =CGRectMake(WIDTH - 80 * wt, 0, 80 * wt, 30 * ht);
        //        [_fullButton setImage:[UIImage imageNamed:@"Full"] forState:(UIControlStateNormal)];
        //        self.navigationController.navigationBarHidden = NO;
        //
        //        self.fullButton.frame = CGRectMake(0, 5 , 20, 20);
        //        _visualEfView.userInteractionEnabled = YES;
        //        _backGroundImage.userInteractionEnabled = YES;
        //        _tableView.alpha = 1;
        //        _seg.hidden = NO;
//    }else {
//        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
//        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
//        _myVedioPlayer.playerLayer.frame = CGRectMake(0, 0, SCREENW, SCREENH);
//        
//        _bottomView.hidden = YES;
    
        
        //       _myVedioPlayer.pl
        
        
        
        
        //        CGRect rect = CGRectMake(0, 64, SCREENW, SCREENH - 64);
        
        //        [_myVedioPlayer setPlayViewWithframe:_rectVedio string:_model.origin_video[@"url_list"][0][@"url"]];
        
        
        //
        //        for (UIView* next = [self superview]; next; next = next.superview) {
        //            UIResponder* nextResponder = [next nextResponder];
        //            if ([nextResponder isKindOfClass:[UIViewController class]]) {
        //                UIViewController *vv = (UIViewController*)nextResponder;
        //                [vv.view addSubview:_myVedioPlayer.playView];
        //            }
        //        }
        
        
        
        //        [self addSubview:_myVedioPlayer.playView];
        
        //        _buttonFullScreen setImage:<#(nullable UIImage *)#> forState:<#(UIControlState)#>
        //        _seg.hidden = YES;
        //        _bottom.hidden = YES;
        
        //        self.navigationController.navigationBarHidden = YES;
        //        _myVedioPlayer.playView.frame = CGRectMake(0, 0, SCREENW, SCREENH);
        //        _tableView.alpha = 0;
        //全屏后底部处理
        //        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT * 5 / 6, SCREEN_WIDTH, SCREEN_HEIGHT / 6);
        //        [_fullButton setImage:[UIImage imageNamed:@"ExFull"] forState:(UIControlStateNormal)];
        
        //全屏后的播放功能view
        //        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //视频大小
        //        self.playerLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //视频进度条 总时间 全屏按钮
        //        self.play.frame = CGRectMake(25, 10, 50, 50);
        //        self.progressSlider.frame = CGRectMake(10 + _play.frame.size.width + 10, 26, SCREEN_WIDTH - 20 - self.timeLable.frame.size.width - _play.frame.size.width - 100, 20);
        //        self.timeLable.frame = CGRectMake(_play.frame.origin.x + 20 + _progressSlider.frame.size.width + 20 + 20, 12, 100, 50);
        //        _fullButton.frame = CGRectMake(5 * wt, 45 * ht, 10 * wt, 30 * ht);
        //        _visualEfView.userInteractionEnabled = YES;
        //        _backGroundImage.userInteractionEnabled = YES;
        
//    }
    
    

    
    
    
    
    
    
    
}



- (void)tapPlayViewAction{
    
//    _progressSlider.hidden = NO;
//    _timeLeftLabel.hidden = NO;
    _playButton.hidden = NO;
    _bottomView.hidden = NO;
//    _playTimesLabel.hidden = YES;
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(ButtonDisappearAction) userInfo:nil repeats:nil];

}




- (void)playButtonAction:(UIButton *)button{
//    _progressSlider.hidden = NO;
//    _timeLeftLabel.hidden = NO;
//    _playTimesLabel.hidden = YES;
    [PLAYMUSIC pausePlay];
    
    if (_p == 0) {
        
        [self.player play];
        
        [_playButton setImage:[UIImage imageNamed:@"iconfont-pause.png"] forState:UIControlStateNormal];
        
        
        _p = 1;
    
        
    }else{
        //    暂停方法
        [self.player pause];
        
        [_playButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang-2.png"] forState:UIControlStateNormal ];
        
        _p = 0;
    }

    
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(ButtonDisappearAction) userInfo:nil repeats:nil];
    
}





- (void)ButtonDisappearAction{
    
    _playButton.hidden = YES;
    
    _bottomView.hidden = YES;
    
//    NSLog(@"!!!!!!!!!!!!!");
}


@end
